package com.kabigon.pdf.itext;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.core.map.MapUtil;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;

public class PdfTemplateExample {
    public static void main(String[] args) {
        // Create a new Document
        Document document = new Document();

        try {

            ClassPathResource resource = new ClassPathResource("/templates/template_202308160018471.pdf");
            // 读取PDF模板文件
            PdfReader pdfReader = new PdfReader(resource.getStream());
            // 创建输出PDF文件
            OutputStream outputStream = new FileOutputStream("output.pdf");
            PdfStamper pdfStamper = new PdfStamper(pdfReader, outputStream);

            // 填充数据到PDF模板中
            Map<String, String> data = MapUtil.newHashMap();
            data.put("now_time", DateUtil.now());
            data.put("useraname", "张杰");
            data.put("number", "123456");
            AcroFields acroFields = pdfStamper.getAcroFields();
            for (Map.Entry<String, String> entry : data.entrySet()) {
                acroFields.setField(entry.getKey(), entry.getValue());
            }

            // 关闭PDF
            pdfStamper.close();
            outputStream.close();
            pdfReader.close();

            System.out.println("PDF template created successfully.");
        } catch (DocumentException | IOException e) {
            e.printStackTrace();
        }
    }
}
